/*
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.pvacameras.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.InvalidKeyException;
import java.security.SignatureException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import com.google.pvacameras.server.config.Config;
import com.google.wallet.online.jwt.FullWalletResponse;
import com.google.wallet.online.jwt.TransactionStatusBody;
import com.google.wallet.online.jwt.TransactionStatusNotification;
import com.google.wallet.online.jwt.util.WalletOnlineService;

/**
 * This servlet handles the Full Wallet Response JWT and decrypts the encrypted
 * card number + cvv using the decrypter class.
 * 
 * Velocity Templates are used for rendering the receipt page.
 * 
 * @author David Peng (gpeng@google.com)
 * 
 */
public class ReceiptServlet extends HttpServlet {
	private static final long serialVersionUID = 2294124125211846176L;

	/**
	 * Get handler forwards request to post handler
	 */
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException {
		doPost(req, resp);
	}

	/**
	 * Post handler renders the template generates the receipt and injects the
	 * transaction notification into the template
	 */
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException {

		try {
			String unitprice = req.getParameter("unitprice");
			// Apply the utility service for conversion between Wallet Java objects
			// and JWT
			WalletOnlineService ows = new WalletOnlineService(Config.getMerchantId(),
					Config.getMerchantSecret());

			// parse the FullWallet Response into JsonToken object
			FullWalletResponse fwrResponse = ows.jwtToJava(FullWalletResponse.class,
					req.getParameter("fullWallet"));

			// Create the transaction notification object using the Google
			// transaction ID from FullWallet response
			TransactionStatusBody tsb = new TransactionStatusBody(fwrResponse
					.getResponse().getGoogleTransactionId(),
					TransactionStatusBody.Status.SUCCESS);
			TransactionStatusNotification tsn = new TransactionStatusNotification(tsb);

			// So we don't write to velocity.log
			Velocity.setProperty("runtime.log.logsystem.class",
					"org.apache.velocity.runtime.log.NullLogChute");

			// Escape HTML
			Velocity.setProperty("eventhandler.referenceinsertion.class",
					"org.apache.velocity.app.event.implement.EscapeHtmlReference");
			Velocity.setProperty("eventhandler.escape.html.match", "/.*/");

			// Initialize Velocity Templates
			Velocity.init();
			VelocityContext context = new VelocityContext();

			// Injects the receipt information and the transaction notification JWT
			// into
			// the template
			context.put("receiptEmail", fwrResponse.getResponse().getEmail());
			context.put("notificationJwt", ows.javaToJwt(tsn));
			context.put("receiptPrice", unitprice);
			context.put("totalPrice", Integer.parseInt(unitprice)+9.99+8);

			// Get the response output stream PrintWriter
			PrintWriter pw;
			pw = resp.getWriter();

			// Render the template and output to print stream
			Velocity.mergeTemplate("receipt.vm", "UTF-8", context, pw);
			pw.flush();
			pw.close();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SignatureException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
